package com.bigtomato.tomatochat.dao;

import com.bigtomato.tomatochat.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class UserDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    public boolean isExistUsername(String username) {
        int count = jdbcTemplate.queryForObject("select count(*) from user where username=?", Integer.class, username);
        return count == 0 ? false : true;
    }
    public long getUserCount(){
        String sql="select count(*) from user";
        int count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }
    public boolean userLogin(User user) {
        int count = jdbcTemplate.queryForObject("select count(*) from user where username=? and password=?", Integer.class, user.getUsername(), user.getPassword());
        return count == 0 ? false : true;
    }
    public Map addUser(String username,String password){
        Map<String,String> message=new HashMap<String, String>();
        if(isExistUsername(username)){
            message.put("state","fail");
            message.put("message","注册失败，账号已存在！");
            return message;
        }
        String sql="insert into user (username,password) values('"+username+"','"+password+"')";
        jdbcTemplate.execute(sql);
        message.put("state","success");
        return message;
    }
    public Map addRandUser(){
        String username= "Tomato"+this.getUserCount();
        String password=username;
        Map<String,String> message=addUser(username,password);
        message.put("username",username);
        message.put("password",password);
        return message;
    }
    public String getIdByUsername(String username){
        String sql="select id from user where username="+username;
        String userId=jdbcTemplate.queryForObject(sql,String.class);
        return userId;
    }
}